<template>
  <div>

    <el-card class="box-card">
      <el-row :gutter="20" style="left: 25%;">
        <el-col :span="9">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        <el-button type="primary" @click="toAddItem">添加商品</el-button>
      </el-row>
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" @change="updateStatus(scope.row)" active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="small" @click="updateUserBtn(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteUser(scope.row)"></el-button>
          </template>

        </el-table-column>
      </el-table>

      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum" :page-sizes="[5, 10, 20, 40]" :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="closeDialog">
      <el-form :model="addUserModel" :rules="rules" ref="addUserRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserModel.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserModel.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="密码确认" prop="password2">
          <el-input v-model="addUserModel.password2" type="password"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addUserModel.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserModel.email"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserBtn">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改用户" :visible.sync="updateDialogVisible" width="50%" @close="closeUpdateDialog">
      <el-form :model="updateUserModel" :rules="rules" ref="updateUserRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updateUserModel.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="updateUserModel.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateUserModel.email"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    data() {
      const checkEmail = (rule, value, callback) => {
        const emailRege = /^[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$/
        if (emailRege.test(value)) {
          return callback()
        }
        callback(new Error('请填写正确的邮箱地址'))
      }

      const checkPhone = (rule, value, callback) => {
        const phoneRege = /^1[34578][0-9]{9}$/
        if (phoneRege.test(value)) {
          return callback()
        }
        callback(new Error('请填写正确的手机号'))
      }

      const checkPassword = (rule, value, callback) => {
        if (this.addUserModel.password !== value) return callback(new Error('2次密码输入不一致'))
        callback()
      }
      return {
        queryInfo: {
          query: '',
          pageNum: 1,
          pageSize: 5
        },
        userList: [],
        total: 0,
        dialogVisible: false,
        rules: {
          username: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 30,
              message: '长度在 3 到 30 个字符',
              trigger: 'blur'
            }
          ],
          password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 30,
              message: '长度在 3 到 30 个字符',
              trigger: 'blur'
            }
          ],
          password2: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 30,
              message: '长度在 3 到 30 个字符',
              trigger: 'blur'
            },
            {
              validator: checkPassword,
              trigger: 'blur'
            }
          ],
          phone: [{
              required: true,
              message: '请输入手机号',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 30,
              message: '长度在 3 到 30 个字符',
              trigger: 'blur'
            },
            {
              validator: checkPhone,
              trigger: 'blur'
            }
          ],
          email: [{
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 30,
              message: '长度在 3 到 30 个字符',
              trigger: 'blur'
            },
            {
              validator: checkEmail,
              trigger: 'blur'
            }
          ]
        },
        addUserModel: {
          username: '',
          password: '',
          password2: '',
          email: '',
          phone: ''
        },
        updateDialogVisible: false,
        // 定义修改用户数据封装
        updateUserModel: {}
      }
    },
    methods: {
      async getUserList() {
        const {
          data: result
        } = await this.$http.post('/aj-user/list',this.queryInfo)
        if (result.status !== 200) return this.$message.error('用户列表查询失败')
        this.userList = result.data.rows
        this.total = result.data.total
      },
      async updateStatus(user) {
        const {
          data: result
        } = await this.$http.post(`/aj-user/status`,user)
        if (result.status !== 200) return this.$message.error('用户状态修改失败!')
        this.$message.success('用户状态修改成功!')
      },
      addUserBtn() {
        this.$refs.addUserRef.validate(async valid => {
          if (!valid) return
          const {
            data: result
          } = await this.$http.post('/aj-user/addUser', this.addUserModel)
          if (result.status !== 200) return this.$message.error('用户新增失败')
          this.$message.success('用户新增成功')
          this.dialogVisible = false
          this.getUserList()
        })
      },
      handleSizeChange(pageSize) {
        this.queryInfo.pageSize = pageSize
        this.getUserList()
      },
      handleCurrentChange(pageNum) {
        this.queryInfo.pageNum = pageNum
        this.getUserList()
      },
      closeDialog() {
        this.$refs.addUserRef.resetFields()
      },
      async updateUserBtn(user) {
        this.updateDialogVisible = true
        const {
          data: result
        } = await this.$http.post('/aj-user/id',user)
        if (result.status !== 200) return this.$message.error('用户查询失败')
        this.updateUserModel = result.data
      },
      closeUpdateDialog() {
        this.$refs.updateUserRef.resetFields()
      },
      updateUser() {
        this.$refs.updateUserRef.validate(async valid => {
          if (!valid) return this.$message.error('表单验证没有通过')
          const user = {
            id: this.updateUserModel.id,
            phone: this.updateUserModel.phone,
            email: this.updateUserModel.email
          }
          const {
            data: result
          } = await this.$http.post('/aj-user/updateUserAdmin', user)
          if (result.status !== 200) return this.$message.error('用户修改失败')
          this.$message.success('用户更新成功')
          this.updateDialogVisible = false
          this.getUserList()
        })
      },
      async deleteUser(user) {
        const result = await this.$confirm('此操作将永久删除 ' + user.username + ', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => error)
        if (result !== 'confirm') {
          return this.$message.info('删除取消')
        }
        const {
          data: result2
        } = await this.$http.post(`/aj-user/dlid`,user)
        if (result2.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getUserList()
      },
      toAddItem(){
        this.$router.push("/addItem")
      }
    },
    mounted() {
      this.getUserList()
    }
  }
</script>

<style>

</style>
